<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>放大镜</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      background: #e5e5e5;
    }

    #small {
      width: 576px;
      height: 324px;
      position: absolute;
      left: 18px;
      top: 36px;
    }

    #box {
      width: 172px;
      height: 97px;
      background-color: #878306;
      cursor: crosshair;
      position: absolute;
      top: 0px;
      left: 0px;
      opacity: 0;
    }

    #big {
      width: 576px;
      height: 324px;
      overflow: hidden;
      position: absolute;
      left: 628px;
      top: 56px;
      display: none;
    }
  </style>
</head>

<body>
  <!-- 小图 -->
  <div id="small">
    <img src="./images/smallimage.jpg" />
    <div id="box"></div>
  </div>

  <!-- 大图 -->
  <div id="big">
    <img src="./images/bigimage.jpg" id="img" style="position:absolute; left:0; top:0;" />
  </div>

  <script>
    // 通过ID的形式获取元素
    var small = document.getElementById('small')
    var box = document.getElementById('box')
    var big = document.getElementById('big')
    var img = document.getElementById('img')

    // 给小图绑定鼠标移动事件 e = event 事件对象
    small.onmousemove = function(e)
    {
      // 让盒子和大图显示
      box.style.opacity = 0.5
      big.style.display = 'inline-block'

      // 得到移动的坐标
      // console.log(e.clientX, e.clientY)

      // 获取元素的外边距
      // console.log(small.offsetLeft, small.offsetTop)

      // 盒子的一半 172 / 2 97 / 2
      var x = e.clientX - small.offsetLeft - 86
      var y = e.clientY - small.offsetTop - 48.5

      if (x <= 0) { // 超出 左边
        x = 0
      } else if (x >= 404) { // 右边 小图宽 - 盒子宽 576 - 172
        x = 404
      }

      if (y <= 0) { // 超出 上面
        y = 0
      } else if (y >= 227) { // 324 - 97
        y = 227
      }

      // 设置box盒子的位置坐标
      box.style.left = `${x}px`
      box.style.top = `${y}px`

      // 大图和小图的比率关系计算 小图上移动xpx 然后在大图上移动多少.33333px
      // 大图800/小图576 = 2.0  大图480/小图324 = 2.0 
      img.style.left = `-${x*(800/576)}px`
      img.style.top = `-${y*(480/324)}px`
    }

    // 移出事件
    small.onmouseleave = function () {
      // 让盒子和大图隐藏
      box.style.opacity = 0
      big.style.display = 'none'
    }
  </script>
</body>

</html>